package utils

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
	"tizhi_front/nspel"
	"tizhi_front/response"
)

var tokenKey = []byte("USjqT1UmUkeId1jS9UXhCdG0194OSK")

func SignToken (uid int64) (tokenString string, err error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid": uid,
		"nbf": time.Now().Unix(),
		"exp": time.Now().Add(nspel.TokenDuration).Unix(),
	})
	tokenString, err = token.SignedString(tokenKey)
	return
}

func ValidateToken (tokenInfo *response.TokenInfo) bool {
	token, err := jwt.Parse(tokenInfo.Token, func (token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("parse token failed")
		}
		return tokenKey, nil
	})
	if err != nil {
		return false
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		uid, ok := claims["uid"]
		if !ok {
			return false
		}
		exp, ok := claims["exp"]
		if !ok {
			return false
		}
		uidFloat64, ok := uid.(float64)
		if !ok {
			return false
		}
		uidInt64 := int64(uidFloat64)
		expFloat64, ok := exp.(float64)
		if !ok {
			return false
		}
		expInt64 := int64(expFloat64)
		if uidInt64 != tokenInfo.Uid {
			return false
		}
		if time.Now().Unix() > expInt64 {
			return false
		}
	} else {
		return false
	}
	return true
}
